package version1.part2.Client.netty.nettyinitalizer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import version1.part2.Client.netty.handler.NettyClientHandler;

/**
 * @author Stone
 * @version 1.0.1
 * @date 2025/9/19
 */
public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //初始化，每个SocketChannel都有一个独立的管道，用于定义数据的处理
        ChannelPipeline pipeline = socketChannel.pipeline();
        //消息格式 [长度]【消息体】，解决沾包问题
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
        //计算当前待发送消息的长度，写入到前四个字节中
        pipeline.addLast(new LengthFieldPrepender(4));
        //编码器
        //使用JAVA序列化方式，netty的自带的解码编码支持传输这种结构
        pipeline.addLast(new ObjectEncoder());
        //解码器
        //使用了netty中的ObjectDecoder,用于将字节流解码称JAVA对象
        pipeline.addLast(new ObjectDecoder(new ClassResolver() {
            @Override
            public Class<?> resolve(String className) throws ClassNotFoundException {
                return Class.forName(className);
            }
        }));
        pipeline.addLast(new NettyClientHandler());
    }
}
